package cn.etgps.etgps.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.etgps.etgps.R;
import cn.etgps.etgps.blmanager.TruckManager;
import cn.etgps.etgps.dataEntity.Model;
import cn.etgps.etgps.dataEntity.TruckBean;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.utils.AppUtils;
import cn.etgps.etgps.utils.Constant;
import cn.etgps.etgps.utils.L;
import cn.etgps.etgps.utils.RxSchedulers;
import cn.etgps.etgps.view.SearchView;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by itte on 2015/12/1.
 */
public class MapMarkerActivity extends MapActivity implements AMap.OnMarkerClickListener, SearchView.SearchListener,
        AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter, AMap.OnMapClickListener {

    public static final int PERIOD = 30;

    List<Model> mSearchList = new ArrayList<Model>();
    /**
     * 货车实体的操作类
     */
    private TruckManager mTruckManager = null;
    /**
     * 用于存放数据库中的TruckBean对象列表
     */
    private List<Model> mDatas = null;
    /**
     * 用于存放Marker的设置信息的列表
     */
    private ArrayList<MarkerOptions> mMarkerOptionlist = null;
    /**
     * 用于保存当前marker
     */
    private Marker mCurrentMarker = null;
    /**
     * 访问本地数据库获取数据的线程
     */
    private GetGarageInfoTask mGetGarageInfoTask = null;
    /**
     * 搜索栏点击的搜索对象
     */
    private DoSearchTask mSearchTask = null;
    /**
     * 用于保存Marker的列表
     */
    private ArrayList<Marker> mMarkerList = null;
    /**
     * 用于接收传来的参数
     */
    private TruckBean mTruckBean = null;
    private boolean isFromModel = false;
    private Observable<Long> refreshObservable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setUpMap();
        addMarkersToMap();
        refreshTruckData();
    }

    /**
     * 判断是否是传来的Model参数
     *
     * @return true表示传来一个TruckBean对象
     */
    public void initTransferedModel() {
        if (getIntent().getSerializableExtra("Model") != null) {
            mTruckBean = (TruckBean) getIntent().getSerializableExtra("Model");
            isFromModel = true;
        }
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        initTransferedModel();
        mTitlebarView.initTitleBarInfo("", "", R.drawable.icon_return, "", R.drawable.title_icon_person, true);
        mTitlebarView.setMainClickListener(this, getString(R.string.title_btn_list_mode),
                getString(R.string.title_btn_me));
        mTitlebarView.getSearchView().initSearchView(this, false);
        if (isFromModel) {
            mTitlebarView.getSearchView().setSearchText(mTruckBean.getLicense());
        }
    }

    /**
     * 设置地图监听
     */
    private void setUpMap() {
        mAMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        mAMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        mAMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        mAMap.setOnMapClickListener(this);//设置地图点击监听
    }

    /**
     * 根据有无传参显示不同的marker在地图上
     */
    private void addMarkersToMap() {
        if (isFromModel) {
            mSearchList = new ArrayList<Model>();
            mSearchList.clear();
            mSearchList.add(mTruckBean);
            showDataOnMap(mSearchList);
        } else {
            mGetGarageInfoTask = new GetGarageInfoTask();
            mGetGarageInfoTask.execute();
        }
    }

    /**
     * 定时获取车辆位置信息，并刷新地图
     */
    private void refreshTruckData() {
        refreshObservable = Observable.interval(PERIOD, PERIOD, TimeUnit.SECONDS)
                .compose(RxSchedulers.<Long>io_main_observalbe(rxDisposable));

        refreshObservable.subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                searchDataFromServer("");
                L.i("reload data");
            }
        }, new Consumer<Throwable>() {

            @Override
            public void accept(Throwable throwable) throws Exception {
                L.e(throwable.getMessage());
            }
        });
    }

    /**
     * 地图点击监听
     */
    @Override
    public void onMapClick(LatLng latLng) {
        if (mCurrentMarker != null) {
            mCurrentMarker.hideInfoWindow();
        }
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    /**
     * 自定义marker弹窗
     *
     * @param marker 点击的marker
     * @return 返回弹窗的视图
     */
    @Override
    public View getInfoContents(Marker marker) {
        View infoContent = getLayoutInflater().inflate(R.layout.map_truck_detail_view, null);
        render(marker, infoContent);
        return infoContent;
    }

    /**
     * 设置自定义marker弹窗中的信息及点击监听
     *
     * @param marker 点击的marker
     * @param view   弹窗的自定义视图
     */
    public void render(final Marker marker, View view) {
        mCurrentMarker = marker;
        TextView license_plate = (TextView) view.findViewById(R.id.license_plate);//车牌号
        TextView belonging = (TextView) view.findViewById(R.id.belonging);//自有、外协
        TextView update_time = (TextView) view.findViewById(R.id.update_time);//时间
        TextView speed = (TextView) view.findViewById(R.id.speed);//速度
        TextView direction = (TextView) view.findViewById(R.id.direction);//方向
        TextView acc_state = (TextView) view.findViewById(R.id.acc_state);//状态
        TextView distance = (TextView) view.findViewById(R.id.distance);//距离
        TextView address = (TextView) view.findViewById(R.id.address);//地址
        TextView stopTime = (TextView) view.findViewById(R.id.stopTime);//停车时长
        TextView fuelCost = (TextView) view.findViewById(R.id.fuelCost);//油量
        Button btn_car_info = (Button) view.findViewById(R.id.btn_car_info);//车辆信息按钮
        Button btn_history_truck = (Button) view.findViewById(R.id.btn_history_truck);//历史轨迹按钮
        mTruckBean = (TruckBean) marker.getObject();
        String license = mTruckBean.getLicense();
        if (license.length() > 8) {
            license = license.substring(0, 8) + "...";
        }
        license_plate.setText(license);
        belonging.setText(getString(R.string.truck_belong_self));
        update_time.setText(AppUtils.reFormatTimeWithoutSeconds(mTruckBean.getGpsTime()));
        speed.setText(getString(R.string.item_acc_speed_title) + mTruckBean.getSpeed() + getString(
                R.string.item_acc_speed_unit));
        direction.setText(
                getString(R.string.item_btn_direction_info) + AppUtils.getDirectionString(mTruckBean.getDirection()));
        String accStatus = mTruckBean.getStatus();
        if (accStatus.contains(getString(R.string.label_truck_acc_status_opened))) {
            acc_state.setText(
                    getString(R.string.item_acc_status_title) + getString(R.string.label_truck_acc_status_opened));
        } else if (accStatus.contains(getString(R.string.label_truck_acc_status_closed))) {
            acc_state.setText(
                    getString(R.string.item_acc_status_title) + getString(R.string.label_truck_acc_status_closed));
        } else if (accStatus.contains(getString(R.string.label_truck_acc_status_flameout))) {
            acc_state.setText(
                    getString(R.string.item_acc_status_title) + getString(R.string.label_truck_acc_status_flameout));
        } else if (accStatus.contains(getString(R.string.label_truck_engine_opened))) {
            acc_state.setText(
                    getString(R.string.item_acc_status_title) + getString(R.string.label_truck_engine_opened));
        } else if (accStatus.contains(getString(R.string.label_truck_engine_closed))) {
            acc_state.setText(
                    getString(R.string.item_acc_status_title) + getString(R.string.label_truck_engine_closed));
        } else {
            acc_state.setText(getString(R.string.item_acc_status_title));
        }
        stopTime.setText(getString(R.string.stop_time) + AppUtils.getStopTime(mTruckBean.getStopTime()));
        if (!mTruckBean.getFuel().equals("")) {
            fuelCost.setText(getString(R.string.fuel_cost) + mTruckBean.getFuel() + getString(R.string.percent));
        } else {
            fuelCost.setVisibility(View.GONE);
        }
        if (mTruckBean.getTotalDistance().equals("")) {
            distance.setText(getString(R.string.item_acc_distance_title));
        } else {
            distance.setText(getString(R.string.item_acc_distance_title) + Math.round(
                    Float.parseFloat(mTruckBean.getTotalDistance())) + getString(R.string.item_acc_distance_unit));
        }
        address.setText(mTruckBean.getLocation());
        /**
         * marker弹窗中，车辆信息点击事件
         */
        btn_car_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapMarkerActivity.this, TruckDetailActivity.class);
                intent.putExtra("vid", mTruckBean.getVID());
                startActivity(intent);
            }
        });
        /**
         * marker弹窗中，历史轨迹点击事件
         */
        btn_history_truck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapMarkerActivity.this, TrackReplaySettingActivity.class);
                intent.putExtra("Model", mTruckBean);
                MapMarkerActivity.this.startActivity(intent);
            }
        });
    }

    /**
     * 将列表中的TruckBean对象显示在地图上
     *
     * @param list TruckBean的对象列表
     */
    public void showDataOnMap(List<Model> list) {
        mAMap.clear();
        if (list == null || list.size() == 0) {
            return;
        }
        MarkerOptions markerOptions;
        TruckBean truck;
        mMarkerOptionlist = new ArrayList<MarkerOptions>();
        LayoutInflater mInflater = LayoutInflater.from(this);
        for (int i = 0; i < list.size(); i++) {
            truck = (TruckBean) list.get(i);
            markerOptions = new MarkerOptions();
            LatLng latLng = new LatLng(truck.getLatitude(), truck.getLongitude());
            if (latLng.latitude != 0 && latLng.longitude != 0) {
                View view = mInflater.inflate(R.layout.map_mark_view, null);
                DisplayMetrics dm = new DisplayMetrics();
                android.view.Display display = getWindowManager().getDefaultDisplay();
                display.getMetrics(dm);
                TextView textView = (TextView) view.findViewById(R.id.licence);
                textView.setText(truck.getLicense() + "");
                ImageView image = (ImageView) view.findViewById(R.id.icon);
                image.setImageResource(AppUtils.getDirectionMarkerId(truck.getDirection()));
                markerOptions.position(latLng);//位置
                markerOptions.title("a");
                markerOptions.anchor(0.5f, 0.5f);
                markerOptions.icon(BitmapDescriptorFactory.fromView(view));
                markerOptions.draggable(false);//拖拽
                mMarkerOptionlist.add(markerOptions);
            } else {
                list.remove(i);
                i--;
            }
        }
        mMarkerList = mAMap.addMarkers(mMarkerOptionlist, true);
        for (int i = 0; i < list.size(); i++) {
            mMarkerList.get(i).setObject(list.get(i));
        }
    }

    @Override
    public void doSearch(String key) {
        if (key.equals("")) {
            mAMap.clear();
            if (mDatas == null || mDatas.size() == 0) {
                if (mGetGarageInfoTask != null && mGetGarageInfoTask.getStatus() == AsyncTask.Status.RUNNING) {
                    mGetGarageInfoTask.cancel(true);
                    mGetGarageInfoTask = null;
                }
                mGetGarageInfoTask = new GetGarageInfoTask();
                mGetGarageInfoTask.execute(key);
            }
            showDataOnMap(mDatas);
        } else {
            searchDataFromServer(key);
        }
    }

    private void searchDataFromServer(String key) {
        if (mSearchTask != null && mSearchTask.getStatus() == AsyncTask.Status.RUNNING) {
            mSearchTask.cancel(true);
            mSearchTask = null;
        }
        mSearchTask = new DoSearchTask();
        mSearchTask.execute(key);
    }

    @Override
    public void clickButtonListener(String name) {
        if (name.equals(getString(R.string.title_btn_list_mode))) {
            this.finish();
        } else {
            Intent intent = new Intent(this, MeActivity.class);
            startActivity(intent);
            this.finish();
        }
    }


    /**
     * 访问本地数据库，获取TruckBean的列表对象,将对象显示在地图上
     */
    class GetGarageInfoTask extends AsyncTask<String, Integer, List<Model>> {
        @Override
        protected List<Model> doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            mTruckManager = new TruckManager(MapMarkerActivity.this);
            mDatas = mTruckManager.getTrucksFromLocalDB();
            mTruckManager.closeDBManager();
            return mDatas;
        }

        @Override
        protected void onPostExecute(List<Model> result) {
            super.onPostExecute(result);
            if (result != null) {
                showDataOnMap(mDatas);
            }
            dismissNormalDialog();
        }
    }

    /**
     * 用于搜索服务器上的TruckBean对象，将对象显示在地图上
     */
    class DoSearchTask extends AsyncTask<String, Integer, String> {
        String result = "";

        @Override
        protected String doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            mSearchList.clear();
            mTruckManager = new TruckManager(MapMarkerActivity.this);
            result = mTruckManager.searchTruckFromServer(mSearchList, params[0], 1);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null && result.equals("")) {

                if (mSearchList == null || mSearchList.size() == 0) {
                    mTruckManager.showToastMessage(getString(R.string.search_no_result), 2000);
                }
                showDataOnMap(mSearchList);
            } else if (Constant.CONNECT_TO_SERVER_FAILED.equals(result)) {
                mTruckManager.showToastMessage(getString(R.string.toast_connect_server_failed), 2000);
            } else {
                mTruckManager.showToastMessage(result, 2000);
            }
            dismissNormalDialog();
        }
    }
}

